package com.android.dwt.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.dwt.R;
import com.android.dwt.TaskItem;
import com.android.dwt.R.color;
import com.android.dwt.R.drawable;
import com.android.dwt.R.id;
import com.android.dwt.R.layout;
import com.android.dwt.R.string;
import com.android.dwt.data.GTDApp;
import com.android.dwt.service.DWTService;
import com.android.dwt.util.C;
import com.android.dwt.util.TaskUtil;

public class TaskDetailAct extends Activity
		implements OnClickListener {
	
	private final String TAG = "TaskDetailAct";
	private final int DLG_SELECT_DAY = 1;
	
	private TextView tv_dtl_prior;
	private TextView tv_dtl_task;
	private TextView tv_dtl_list;
	private TextView tv_dtl_prj;
	private LinearLayout ll_dtl_tags;
	private TextView tv_dtl_created;
	private TextView tv_dtl_se;
	private TextView tv_dtl_repeat;
	private TextView tv_dtl_remind;
	
	private GTDApp ga;
	private Calendar calCur;
//	private HashMap<String, Object> hmCur;
	private int mListIndex;
	private int taskStatus;
	private TaskItem task;
	private long mRowId;
	private DWTService mService;
	private boolean mBound;
	private Calendar mRemind;
	private Calendar mSelectDay;
	
	private Resources mRsrc;
	
	private SimpleDateFormat mSdfDate = new SimpleDateFormat("yyyy-MM-dd");
	private SimpleDateFormat mSdfTime = new SimpleDateFormat("HH:mm");
	private SimpleDateFormat mSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		Log.e(TAG, "onCreate is called!");
		
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.task_detail);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_cmn);
		
		ga = (GTDApp) getApplication();
//		calCur = Calendar.getInstance();
		mSelectDay = Calendar.getInstance();
		
		mRsrc = getResources();
		
		mRowId = getIntent().getLongExtra("row_id", -1);
//		task = (TaskItem) getIntent().getSerializableExtra("task");
		task = ga.getDbta().getTaskItem(mRowId);
//		mListIndex = (Integer) getIntent().getIntExtra("list_index", -1);
		mListIndex = TaskUtil.getListIndex(ga.mList, task.getListName());
		
		String rmd = task.getRemind();
		if (rmd.length() > 0) {
			
			mRemind = Calendar.getInstance();		// only when remind is set, $mRemind is not null
			
			try {
				
				Date date = mSdf.parse(rmd);
				mRemind.setTime(date);
				
			} catch (ParseException e) {
				
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		taskStatus = task.getCompletedStatus();
		
//		hmCur = (HashMap<String, Object>) getIntent().getSerializableExtra("selected_task");
//		mListIndex = (int) getIntent().getIntExtra("list_index", 0);
//		taskStatus = (int) getIntent().getIntExtra("task_status", C.TASK.UNCOMPLETED);
		
		initView();
		
		fillData();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		Log.e(TAG, "onDestroy is called!");
		
		/*if (mBound)
			unbindService(TaskDetailAct.this);*/
		
//		Log.e(TAG, "unbind service successfully");
	}
	
	private void fillData() {
		
		boolean isAgenda = false;
		
		String prior = task.getPrior();
		if (prior.equals("无")) {
			
			tv_dtl_prior.setBackgroundColor(0xffffffff);
			
		} else if (prior.equals("高")) {
			
			tv_dtl_prior.setBackgroundColor(mRsrc.getColor(R.color.high_prior));
			
		} else if (prior.equals("中")) {
			
			tv_dtl_prior.setBackgroundColor(mRsrc.getColor(R.color.medium_prior));
			
		} else if (prior.equals("低")) {
			
			tv_dtl_prior.setBackgroundColor(mRsrc.getColor(R.color.low_prior));
		}
		
		// set task name
		tv_dtl_task.setText(task.getTaskName());
		
		// set task list
		String strList = task.getListName();
		if (strList.equals(getString(R.string.agenda))) {
			
			isAgenda = true;
		}
		tv_dtl_list.setText("+" + strList);
		
		String project = task.getProject();
		if (project.equals(ga.getProjects().get(0)))
			tv_dtl_prj.setText("");
		else
			tv_dtl_prj.setText("#"+project);
		
		String strTag = task.getTags();
		if (strTag.length() > 0) {
			
			String[] tags = strTag.split(",");		// if only one tag, return this tag
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(MarginLayoutParams.WRAP_CONTENT,
					MarginLayoutParams.WRAP_CONTENT);
			lp.setMargins(0, 0, 6, 0);
			
			// at least one string
			for (int i=0; i<tags.length; i++) {
				
				TextView tv = new TextView(this);
				
				tv.setText(tags[i].trim());
				tv.setTextColor(0xffffffff);
				tv.setPadding(3, 3, 3, 3);
				tv.setGravity(Gravity.CENTER);
				tv.setBackgroundDrawable(mRsrc.getDrawable(R.drawable.bg_tag));
				
				ll_dtl_tags.addView(tv,lp);
			}
			
		} else {
			
			LinearLayout ll_head = ((LinearLayout) findViewById(R.id.ll_head));
			ll_head.removeView(ll_dtl_tags);
		}
		tv_dtl_created.setText(task.getCreated());
		
		String context = task.getContext();
		String pos = task.getPosition();
		
		LinearLayout ll_second = ((LinearLayout) findViewById(R.id.ll_second));
		LinearLayout ll_dtl_agenda = ((LinearLayout) findViewById(R.id.ll_dtl_agenda));
		
		tv_dtl_remind = ((TextView) findViewById(R.id.tv_dtl_remind));
		String remind = task.getRemind();
		
		boolean head = false;
		// agenda
		if (isAgenda) {
			
			String time;
			
			head = true;
			
			if (task.isAllDay()) {		// all day task
				
				time = ((task.getStartTime()).split(" "))[0]
						+ " ~ " + ((task.getEndTime()).split(" "))[0];
				
			} else {
				
				String endTime = task.getEndTime();
				if (endTime.length() > 1) {  	// end time may be " " 
					
					time = task.getStartTime() + " ~ " + endTime;
					
				} else {
					
					time = task.getStartTime();
				}
				
			}
			tv_dtl_se.setText(time);
			
			String repeat = task.getRepeat();
			if (repeat.length() == 0) {
				
				ll_dtl_agenda.removeView(tv_dtl_repeat);
				
			} else {
				
				tv_dtl_repeat.setText(repeat);
			}
			
			if (remind.length() == 0) {		// no remind in this task
				
				ll_dtl_agenda.removeView(tv_dtl_remind);
				
			} else {
				
				if (task.isAllDay())	// all day task
					tv_dtl_remind.setText("于 "+remind+" 提醒");
				else
					tv_dtl_remind.setText(remind+" 提醒");
			}
			
			/*if (context.length()>0
					|| !pos.equals(ga.getPositions().get(0).getPlace())) {
				
				((TextView) findViewById(R.id.tv_divider1)).setVisibility(View.VISIBLE);
				
			} else {
				
				((TextView) findViewById(R.id.tv_divider1)).setVisibility(View.GONE);
			}*/
			
		} else {			// no agenda task
			
			Log.e(TAG, "start time: "+task.getStartTime());
			Log.e(TAG, "end time: "+task.getEndTime());
			Log.e(TAG, "repeat string: "+task.getRepeat());
			
			if (remind.length() == 0) {		// no remind
				
				ll_second.removeView(ll_dtl_agenda);
				
			} else {		// there is remind
				
				head = true;
				
				ll_dtl_agenda.removeView(tv_dtl_se);
				ll_dtl_agenda.removeView(tv_dtl_repeat);
				
				tv_dtl_remind.setText("于 "+remind+" 提醒");
				
				/*if (context.length()>0
						|| !pos.equals(ga.getPositions().get(0).getPlace())) {
					
					((TextView) findViewById(R.id.tv_divider1)).setVisibility(View.VISIBLE);
					
				} else {
					
					((TextView) findViewById(R.id.tv_divider1)).setVisibility(View.GONE);
				}*/
				
			}
			
		}
		
		// context
		TextView tv_dtl_context = ((TextView) findViewById(R.id.tv_dtl_context));
		if (context.equals(ga.getContexts().get(0))) {		// no context
			
			LinearLayout ll_dtl_context = ((LinearLayout) findViewById(R.id.ll_dtl_context));
			ll_second.removeView(ll_dtl_context);
//			ll_second.removeView(((TextView) findViewById(R.id.tv_divider2)));
			
			((TextView) findViewById(R.id.tv_divider1)).setVisibility(View.GONE);
			
		} else {
			
			if (head) {
				
				((TextView) findViewById(R.id.tv_divider1)).setVisibility(View.VISIBLE);
			}
			
			tv_dtl_context.setText(context);
			
			/*if (pos.equals(ga.getPositions().get(0).getPlace())) {
				
				((TextView) findViewById(R.id.tv_divider2)).setVisibility(View.GONE);
			}*/
			
		}
		
		// position
		TextView tv_dtl_pos = ((TextView) findViewById(R.id.tv_dtl_pos));
		if (pos.equals(ga.getPositions().get(0).getPlace())) {
			
			LinearLayout ll_pos = ((LinearLayout) findViewById(R.id.ll_pos));
			ll_second.removeView(ll_pos);
			
			((TextView) findViewById(R.id.tv_divider2)).setVisibility(View.GONE);
			
		} else {
			
			if (head) {
				
				((TextView) findViewById(R.id.tv_divider2)).setVisibility(View.VISIBLE);
			}
			
			tv_dtl_pos.setText(pos);
		}
		
		// task note
		TextView tv_dtl_note = ((TextView) findViewById(R.id.tv_dtl_note));
		String note = task.getTaskNote();
		if (note.length() > 0) {
			
			tv_dtl_note.setText(note);
			
		} else {
			
			LinearLayout ll_content = ((LinearLayout) findViewById(R.id.ll_content));
			LinearLayout ll_dtl_note = ((LinearLayout) findViewById(R.id.ll_dtl_note));
			ll_content.removeView(ll_dtl_note);
		}
		
	}
	
	private void initView() {
		
		((TextView) findViewById(R.id.tv_title)).setText("查看任务");
		((ImageButton) findViewById(R.id.btn_new)).setVisibility(View.INVISIBLE);
		
		ImageButton btn_return = ((ImageButton) findViewById(R.id.btn_return));
		btn_return.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		btn_return.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					
					v.setBackgroundResource(R.drawable.back_pressed);
					
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					
					v.setBackgroundResource(R.drawable.back);
				}

				return false;
			}
			
		});
		
		tv_dtl_prior = ((TextView) findViewById(R.id.tv_dtl_prior));
		tv_dtl_task = ((TextView) findViewById(R.id.tv_dtl_task));
		tv_dtl_list = ((TextView) findViewById(R.id.tv_dtl_list));
		tv_dtl_prj = ((TextView) findViewById(R.id.tv_dtl_prj));
		ll_dtl_tags = ((LinearLayout) findViewById(R.id.ll_dtl_tags));
		tv_dtl_created = ((TextView) findViewById(R.id.tv_dtl_created));
		
		tv_dtl_se = ((TextView) findViewById(R.id.tv_dtl_se));
		tv_dtl_repeat = ((TextView) findViewById(R.id.tv_dtl_repeat));
		
		if (taskStatus == C.TASK.CANCELLED) {
			
			LinearLayout ll_dtl_top = ((LinearLayout) findViewById(R.id.ll_dtl_top));
			LinearLayout ll_btn = ((LinearLayout) findViewById(R.id.ll_btn));
			ll_dtl_top.removeView(ll_btn);
			
		} else {
			
			Button btn_move = ((Button) findViewById(R.id.btn_move));
			btn_move.setOnClickListener(this);
			
			Button btn_del = ((Button) findViewById(R.id.btn_del));
			btn_del.setOnClickListener(this);
			
			((Button) findViewById(R.id.btn_edit)).setOnClickListener(this);
		}
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		
			case R.id.btn_edit:
				
				/*Intent itt = new Intent(TaskDetailAct.this, NewTaskAct.class);
				
				itt.putExtra("row_id", mRowId);
				itt.putExtra("task_data", task);
				itt.putExtra("list_index", mListIndex);
				itt.putExtra("selected_date", TaskDetailAct.this.getIntent().getStringExtra("selected_date"));
				
				startActivityForResult(itt, 0);
				
				finish();*/
				
				ga.mFinishAct = true;
				TaskUtil.editTask(TaskDetailAct.this, mListIndex, mRowId);
				
				break;
				
			case R.id.btn_del:
				
//				removeTask();
				
				ga.mFinishAct = true;
				TaskUtil.removeTask(TaskDetailAct.this, mListIndex, mRowId);
				
				break;
				
			case R.id.btn_move:
				
//				moveTask();
				
				ga.mFinishAct = true;
				TaskUtil.moveTask(TaskDetailAct.this, mListIndex, mRowId);
				
				break;
				
			default:
				break;
		}
	}
	
	/*private void removeTask() {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(TaskDetailAct.this);
		
		builder.setTitle("确定要删除该任务吗");
		
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				// bind service 
				Intent i = new Intent(TaskDetailAct.this, DWTService.class);
				bindService(i, TaskDetailAct.this, BIND_AUTO_CREATE);
				
//				long posInTable = getIntent().getLongExtra("row_id", 0);
				TaskItem ti = ga.getDbta().getTaskItem(mRowId);
				
				ti.setCompletedStatus(C.TASK.CANCELLED);
				ga.getDbta().updateTask(mRowId, ti);
				
				
				// update the counter
				int count = (Integer) ga.lists.get(mListIndex).get("item_count");
				ga.lists.get(mListIndex).put("item_count", count-1);
				
				SharedPreferences prefs = getSharedPreferences(GTDApp.strList, GTDApp.MODE);
				Editor editor = prefs.edit();
				
				editor.putInt("List_count["+mListIndex+"]", count-1);
				editor.commit();
				
				
				dialog.dismiss();
				finish();
			}
			
		});
		
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		
		builder.show();
	}
	
	private void moveTask() {
		
		ArrayList<String> als = new ArrayList<String>();
		ArrayList<ListItem> al = ga.getListItems();
		
		for (int i=0; i<al.size(); i++)
			als.add(al.get(i).getListName());
		final String[] listItems = (String[]) als.toArray(new String[als.size()]);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(TaskDetailAct.this);
		
		builder.setTitle("移动到");
		
		builder.setSingleChoiceItems(listItems, mListIndex,
				new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(final DialogInterface dialog, final int item) {
				
				// TODO Auto-generated method stub
				if (item != mListIndex) {		// select different list
					
					if (item == GTDApp.AGENDA) {	// move a non-agenda task to agenda task
						
						OnDateSetListener dateListener = new OnDateSetListener() {
							
							@Override
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
								
								Log.e(TAG, "onDateSet: "+year+" "+monthOfYear+" "+dayOfMonth);
								
								// TODO Auto-generated method stub
								mSelectDay.set(year, monthOfYear, dayOfMonth, 0, 0);
								
								task.setAllDay(true);
								task.setStartTime(mSdf.format(mSelectDay.getTime()));
								task.setEndTime(mSdf.format(mSelectDay.getTime()));
								task.setRepeat("");	// no repeat
								
								task.setListName(listItems[item]);
								ga.getDbta().updateTask(mRowId, task);
								
								// update the counter
								int count1 = (Integer) ga.lists.get(mListIndex).get("item_count");
								ga.lists.get(mListIndex).put("item_count", count1-1);
								
								int count2 = (Integer) ga.lists.get(item).get("item_count");
								ga.lists.get(item).put("item_count", count2+1);
								
								SharedPreferences prefs = getSharedPreferences(GTDApp.strList, GTDApp.MODE);
								Editor editor = prefs.edit();
								
								editor.putInt("List_count["+mListIndex+"]", count1-1);
								editor.putInt("List_count["+item+"]", count2+1);
								editor.commit();
								
								dialog.dismiss();
								finish();
							}
							
						};
						
						DatePickerDialog dateDlg = new DatePickerDialog(
								TaskDetailAct.this,
		                        dateListener,
		                        mSelectDay.get(Calendar.YEAR),
								mSelectDay.get(Calendar.MONTH),
								mSelectDay.get(Calendar.DAY_OF_MONTH));
						
						dateDlg.setOnDismissListener(new OnDismissListener() {
							
							@Override
							public void onDismiss(DialogInterface dialog) {
								// TODO Auto-generated method stub
								
								Log.e(TAG, "DatePickerDialog is dismissed!");
								
								dialog.dismiss();
							}
						});
						
						dateDlg.show();
						
					} else {		// move to a non-agenda task
						
						task.setListName(listItems[item]);
						ga.getDbta().updateTask(mRowId, task);
						
						// update the counter
						int count1 = (Integer) ga.lists.get(mListIndex).get("item_count");
						ga.lists.get(mListIndex).put("item_count", count1-1);
						
						int count2 = (Integer) ga.lists.get(item).get("item_count");
						ga.lists.get(item).put("item_count", count2+1);
						
						SharedPreferences prefs = getSharedPreferences(GTDApp.strList, GTDApp.MODE);
						Editor editor = prefs.edit();
						
						editor.putInt("List_count["+mListIndex+"]", count1-1);
						editor.putInt("List_count["+item+"]", count2+1);
						editor.commit();
						
						dialog.dismiss();
						finish();
					}
					
				} else {		// select the same list
					
					dialog.dismiss();
				}
				
			}
			
		});
		
		builder.show();
	}*/
	
	/*@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		// TODO Auto-generated method stub

		Log.e(TAG, "bind successfully!");
		
		MyBinder binder = (MyBinder) service;
        mService = binder.getService();
        mBound = true;
        
    	if (mOldRemind!=null && mOldRemind.after((Calendar.getInstance())))		// remove previous alarm
    		mService.removeSingleAlarm(mRowId);		// the alarm exists in sharedpreferences
    	
    	if (mSetRemind) {		//  current alarm exists
    		mService.setTaskID(mID);
			mService.setRemindTime(mRmd);
			mService.setAlarm();
    	}
    	
        Log.e(TAG, "now will remove alarm of task: "+mRowId);
        
        if (mRemind!=null && mRemind.after((Calendar.getInstance()))) {
        	
        	mService.removeSingleAlarm(mRowId);
        }
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		mService = null;
		mBound = false;
	}*/
	
}
